package com.margo.project.web.mvcconfig.converter;

import java.lang.reflect.Field;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.margo.project.web.mvcconfig.model.MargoConverterVO;

@Component
public class PulldownValueConverter implements Converter<MargoConverterVO ,MargoConverterVO>{

	private Logger logger=LoggerFactory.getLogger(PulldownValueConverter.class);	
	
	@Override
	public MargoConverterVO convert(MargoConverterVO source) {
		String pulldown=source.getPulldownField();
		Field field;
		try {
			field = source.getClass().getDeclaredField(pulldown);
			field.setAccessible(true);
			String value = (String) field.get(source);
    		field.set(source, deserialize(value,source.getPulldownLength()));
		} catch (Exception e) {
			logger.error("#######属性设置异常######",e);
		} 
		return source;
	}
	
	public String deserialize(String value,int length) {
		if (value != null && !StringUtils.isEmpty(value)) {
			String strIds = "";
			String[] objIdLists = StringUtils.split(value, ";");
			if(objIdLists.length==length) {
				return null;
			}
			for (String id : objIdLists) {
				if (!StringUtils.isEmpty(strIds)) {
					strIds = strIds + ",'" + id + "'";
				} else {
					strIds = "'" + id + "'";
				}
			}
			return strIds;
		} else {
			return null;
		}
	}

}
